const maxImgIndex = 15;
let curTargetIndex = null;
let isGameOver = false;

function $(selector) {
  return document.querySelector(selector);
}

function $$(selector) {
  return document.querySelectorAll(selector);
}

const panel = $(".panel");
const initImg = $("#initImg");
const resultImg = $("#resultImg");
const dictionary = $(".dictionary");

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

function init() {
  curTargetIndex = getRandom(0, maxImgIndex);
  dictionary.innerHTL = "";

  for (let i = 0; i < 100; i++) {
    let imgIndex = null;
    if (i % 9 === 0) {
      imgIndex = curTargetIndex;
    } else {
      imgIndex = getRandom(0, maxImgIndex);
    }

    dictionary.innerHTML += `<div class="item">
      <span class="number">${i}</span>
      <span class="value">
        <img src="./images/values/${imgIndex}.png">
      </span>
    </div>`;
  }
}

function panelTransitionend() {
  initImg.style.opacity = 0;
  resultImg.style.opacity = 1;
  resultImg.src = `./images/values/${curTargetIndex}.png`;
  isGameOver = true;
}

function panelClick(e) {
  const currentTarget = e.currentTarget;
  if (!isGameOver) {
    currentTarget.style.transition = "all 2s";
    currentTarget.style.transform = "rotate(360deg)";
    panel.addEventListener("transitionend", panelTransitionend);
  } else {
    if (window.confirm("是否在完一次?")) {
      init();
      isGameOver = false;
      initImg.style.opacity = 1;
      resultImg.style.opacity = 0;
      currentTarget.setAttribute("style", "");
      panel.removeEventListener("transitionend", panelTransitionend);
    }
  }
}

function bindEvent() {
  panel.onclick = panelClick;
}

function main() {
  init();
  bindEvent();
}

main();
